/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package station3d;

import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;
import java.io.*;
import javax.media.opengl.GL;
import station3d.graphics.Mesh;
import station3d.graphics.Terrain;

/**
 * Správce zdrojů aplikace.
 * @author Martin
 */
public class ResourceManager {


    public InputStream getResource(String filename) throws ResourceError {
        InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
        if (is == null) {
            throw new ResourceError(filename, "File doesn't exist.");
        }
        return is;
    }

    /**
     * Načte mesh ze zadaného souboru.
     * @param filename jméno souboru
     * @return načtený mesh
     * @throws ResourceError pokud soubor neexistuje nebo dojde k jiné chybě
     */
    public Mesh loadMesh(String filename, boolean doubleFaces) throws ResourceError {
        try {
            Mesh mesh = Mesh.loadFromFile(getResource(filename), doubleFaces, false, 1);
            return mesh;
        }
        catch (IOException e) {
            throw new ResourceError(filename, "IO Exception.", e);
        }
    }


    public Terrain loadTerrain(String filename,
            float meshScale,
            Texture largeTexture,
            Texture detailTexture,
            float detailTextureScale
            ) throws ResourceError {
        try {
            Mesh terrainMesh = Mesh.loadFromFile(getResource(filename), false, true, detailTextureScale);
            Terrain terrain = new Terrain(terrainMesh, meshScale);
            terrain.setLargeTexture(largeTexture);
            terrain.setDetailTexture(detailTexture);
            return terrain;
        }
        catch (IOException e) {
            throw new ResourceError(filename, "IO Exception.", e);
        }
    }

    public Texture loadTexture(String filename) throws ResourceError {
        return loadTexture(filename, true);
    }

    public Texture loadTexture(String filename, boolean mipmapped) throws ResourceError {
        try {
            Texture texture = TextureIO.newTexture(getResource(filename), mipmapped, null);
            texture.setTexParameteri(GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
            texture.setTexParameteri(GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
            return texture;
        }
        catch (IOException e) {
            throw new ResourceError(filename, "Bad texture format.", e);
        }
    }


}
